class Timer
  class << self
    attr_reader :timers
    
    def <<(timer)
      @timers ||= []
      @timers << timer
    end
    
    def after(milliseconds, &block)
      timer = Timer.new &block
      timer.next_call += milliseconds
    end
    
    def clear
      @timers = []
    end
    
    def delete(timer)
      @timers.delete timer if @timers
    end
    
    def every(milliseconds, &block)
      Timer.new milliseconds, &block
    end
    
    def update_all
      @timers.each { |timer| timer.update } if @timers
    end
  end
  
  attr_accessor :next_call

  def initialize(milliseconds=nil, &block)
    @block = block
    @milliseconds = milliseconds
    @next_call = now
    @next_call += @milliseconds if @milliseconds
    Timer << self
  end
  
  def delete
    Timer.delete self
  end
  
  def pause
    @paused = true
  end
  
  def resume
    @next_call += Gosu::milliseconds
    @paused = false
  end
  
  def update
    return if @paused
    while @next_call and @next_call.yet?
      @next_call = @milliseconds ? @next_call + @milliseconds : nil
      @block.call(self)
    end
    delete unless @next_call
  end
end
